<template>
    <div>
        <div class="activity-right">
            <h3>修改活动</h3>
            <div class="select_type">
                <el-form ref="form" :rules="rules" v-if="form" :model="form" label-width="120px">
                    <el-form-item label="活动名称:" prop="name">
                        <el-input style="width:400px" prop="name" v-model="form.name" type="text" placeholder="请输入活动名称" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="选择品牌:" prop="brandList">
                        <el-select style="width:400px" filterable v-model="form.brandId" @change="getBrand()" placeholder="选择品牌">
                            <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <!-- <el-form-item label="品牌标题:" prop="brandTitle">
                        <el-input style="width:400px" prop="brandTitle" v-model="form.brandTitle" type="text" placeholder="请输入活动标题" clearable></el-input>
                    </el-form-item> -->
                    <el-form-item label="品牌介绍:" prop="brandStory">
                        <el-input style="width:400px" :maxlength="120" type='textarea' prop="brandStory"  v-model="form.brandStory" :rows="5" placeholder="请输入品牌故事(120个汉字以内)" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="品牌logo:" prop="imgUrl" v-loading="uploadLoading">
                        <div class="prevImg" v-if="form.imgUrl">
                            <img width="200" :src="form.imgUrl" alt="">
                            <i class="el-icon-error" @click="deleteImgList()"></i>
                        </div>
                        <template v-if="form.imgUrl == ''">
                            <div class="upload">
                                <input class="file" name="file" type="file" accept="image/png,image/gif,image/jpeg" @change="upload($event)" />
                                <i class="el-icon-plus"></i>
                            </div>
                        </template>
                        <template v-else>
                            <div class="upload" style="display:inline-block">
                                <input class="file" name="file" type="file" accept="image/png,image/gif,image/jpeg" @change="upload($event)" />
                                <span>点击更换</span>
                            </div>
                        </template>
                        <p class="red" style="margin-top:10px;line-height:1.5">
                            <small>请选择品牌logo图片上传(最多1张)</small>
                        </p>
                        <p class="red" style="margin-top:10px;line-height:1.5">
                            <small>建议尺寸：不小于200*200方图</small>
                        </p>
                    </el-form-item>
                    <el-form-item label="品牌标签:" prop="brandTag">
                        <el-input style="width:200px;margin-right:10px;" prop="brandTag" :maxlength="8"  type="text" v-for="itemtag in form.brandTag" :key="itemtag.id" v-model="itemtag.val"  placeholder="请输入品牌标签(8个字)" clearable></el-input>
                        <section ><el-button style="margin-left:0;margin-top:10px;" v-if="form.brandTag.length<4" @click="addBtn">新增</el-button></section>
                    </el-form-item>
                    <el-form-item label="活动公告:" prop="notice">
                        <el-input style="width:400px" type='textarea' prop="notice" v-model="form.notice" placeholder="请输入活动公告" :rows="5" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="活动备注:" prop="remark">
                        <el-input style="width:400px" type='textarea' prop="remark" v-model="form.remark" :rows="5" placeholder="请输入活动备注" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="活动排序:" prop="sort">
                        <el-input style="width:400px" prop="sort" v-model="form.sort" type="text" placeholder="请输入活动序号，1-10整数且10最大" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="开始时间:" prop="startTime">
                        <template>
                            <div class="block">
                                <el-date-picker v-model="startTime" type="datetime" style="width:400px" @change="handleChange" placeholder="选择日期时间">
                                </el-date-picker>
                            </div>
                            <small style="color:#999">可手动输入，例如：日期20180809 时间120000（2018-08-09 12:00:00）</small>
                        </template>
                    </el-form-item>
                    <el-form-item label="结束时间:" prop="endTime">
                        <template>
                            <div class="block">
                                <el-date-picker v-model="endTime" type="datetime" style="width:400px" @change="handleChange" placeholder="选择日期时间">
                                </el-date-picker>
                            </div>
                            <small style="color:#999">可手动输入，例如：日期20180809 时间120000（2018-08-09 12:00:00）</small>
                        </template>
                    </el-form-item>
                    <el-form-item v-if="timeStatus==1" label="活动状态:" prop="status">
                        <el-select class="input" style="width:400px" v-model="form.status" placeholder="选择活动状态">
                            <el-option v-for="item in option" :key="item.id" :label="item.label" :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item v-else label="活动状态:" prop="status">
                        <template>{{form.status==0 ? '展示' : (form.status==1 ? '售卖中' : '结束')}}</template>
                    </el-form-item>
                    <!-- 活动banner -->
                    <el-form-item prop="imageList" label="活动banner:" class="uploadWrap" v-loading="uploadLoading1">
                        <div class="prevImg" :key="item.id" v-for="(item,index) in form.imageList" v-if="form.imageList && form.imageList.length > 0">
                            <img height="200" :src="item" alt="">
                            <i class="el-icon-back" title="位置前进一位" v-if="index != 0" @click="goToPrev(index)"></i>
                            <i class="el-icon-error" @click="deleteImgList1(index)"></i>
                        </div>
                        <template v-if="form.imageList && form.imageList.length < 1">
                            <div class="upload">
                                <input class="file" name="file" type="file" accept="image/png,image/gif,image/jpeg" multiple @change="uploadimg($event)" />
                                <i class="el-icon-plus"></i>
                            </div>
                        </template>
                        <p class="red" style="margin-top:10px;line-height:1.5">
                            <small>请选择1张品牌图片上传(最多1张)</small>
                        </p>
                        <p class="red" style="margin-top:10px;line-height:1.5">
                            <small>建议尺寸：宽度不小于400</small>
                        </p>
                    </el-form-item>
                    <!-- 活动介绍-9 -->
                    <el-form-item prop="imageActivityList" label="活动介绍:" class="uploadWrap" v-loading="uploadLoading1">
                        <div class="prevImg" :key="item.id" v-for="(item,index) in form.imageActivityList" v-if="form.imageActivityList && form.imageActivityList != ''">
                            <img height="200" :src="item" alt="">
                            <i class="el-icon-back" title="位置前进一位" v-if="index != 0" @click="goToPrev1(index)"></i>
                            <i class="el-icon-error" @click="deleteImgList2(index)"></i>
                        </div>
                        <template v-if="form.imageActivityList && form.imageActivityList.length < 9 || form.imageActivityList==null">
                            <div class="upload">
                                <input class="file" name="file" type="file" accept="image/png,image/gif,image/jpeg" multiple @change="uploadActimg($event)" />
                                <i class="el-icon-plus"></i>
                            </div>
                        </template>
                        <p class="red" style="margin-top:10px;line-height:1.5">
                            <small>请选择活动图片上传(最多9张)</small>
                        </p>
                        <p class="red" style="margin-top:10px;line-height:1.5">
                            <small>建议尺寸：宽度不小于400</small>
                        </p>
                    </el-form-item>
                </el-form>
                <section class='right-btn' style="float:right">
                    <el-button type="primary" @click="handleSubmit">确定</el-button>
                    <el-button type="primary" style="margin-left:10px" @click="$router.go(-1)">返回</el-button>
                </section>
            </div>
        </div>
    </div>
</template>

<script>
import leftBar from "../commonComponents/leftBar.vue";
import { getActivityDetail, getQiniuToken, qiniuBaseUrl, editActivity, getBrandList, getBrandById } from "../../data/postData";
export default {
    components: {
        leftBar
    },
    mounted() {
        var params = {
            data: {
                storeNo: this.user.storeNo,
                id: this.$route.params.id
            }
        };
        this.$fetch.post(getActivityDetail, params).then(res => {
            this.form = res.data;
            res.data.imageList &&
                res.data.imageList.forEach(item => {
                    this.imageArr.push(item.mediaUrl);
                });
            this.form.imageList = this.imageArr;
            this.startTime = new Date(res.data.startTime);
            this.endTime = new Date(res.data.endTime);
            this.form.brandTag = res.data.brandTag.split(',')
            var brandtag1=[];
            this.form.brandTag.forEach(item=>{
                brandtag1.push({
                    id:item,
                    val:item
                })
            })
            this.form.brandTag = brandtag1
            if(res.data.imageActivityList != ''){
                this.form.imageActivityList = res.data.imageActivityList.split(',')
            }else{
                this.form.imageActivityList = []
            }

        }).catch(err => {});

        this.getBrandList()
    },
    data() {
        return {
            mt30: {
                "margin-top": "30px"
            },
            user: JSON.parse(localStorage.getItem("ddaigoUser")),
            form: {
                name: "",
                notice: "",
                sort: "",
                status: "",
                remark: "",
                imgUrl: "",
                brandId:'',
                brandTag:[],
                imageActivityList:[]
            },
            brandList:[],
            timeStatus: 0,
            imageList: [],
            imageArr: [],
            startTime: "",
            endTime: "",
            option: [
                {
                    id: 0,
                    value: 0,
                    label: "展示"
                },
                {
                    id: 1,
                    value: 1,
                    label: "售卖中"
                },
                {
                    id: 2,
                    value: 2,
                    label: "结束"
                }
            ],
            rules: {
                name: [{required: true, message: "请输入活动名称", trigger: "blur"}],
                sort: [{ required: true, message: "请输入活动序号",trigger: "blur"}],
                startTime: [{ required: true, message: "请选择活动开始时间", trigger: "blur" }],
                endTime: [{ required: true, message: "请选择活动结束时间", trigger: "blur" }],
                status: [{ required: true, message: "请选择活动状态", trigger: "blur"}],
                notice: [{required: true, message: "请输入活动公告", trigger: "blur"}],
                imgUrl: [{ required: true, message: "选择活动图片", trigger: "blur" }],
                brandTitle: [{ required: true, message: "请输入品牌标题", trigger: "blur"}],
                brandStory: [{required: true, message: "请输入品牌故事",trigger: "blur" }],
                imageList: [{ required: true, message: "请上传品牌图片集",trigger: "blur"}],
            },
            uploadLoading: false,
            uploadLoading1: false,
            tableLoading: false,
            files: []
        };
    },

    methods: {
        addBtn(){
            this.form.brandTag.push({id:this.form.brandTag.length,val:''})
        },
        //获取品牌列表
        getBrandList(){
            var params = {
                "data": {
                    page:1,
                    size:1000
                }
            }
            this.$fetch.post(getBrandList,params).then(res=>{
                this.brandList = res.data
            }).catch(err=>{

            })
        },
        getBrand(){
             var params = {
                "data": {
                    "brandId":''+this.form.brandId
                }
             }
             this.$fetch.post(getBrandById, params).then(res=>{
                 this.form.brandStory = res.data.story
                 this.form.imgUrl = res.data.url
             }).catch(err=>{

             })
        },
        handleChange() {
            let nowStartTime = +new Date(this.startTime).getTime();
            let nowTime = +new Date().getTime();
            let nowEndTime = +new Date(this.endTime).getTime();
            if (nowEndTime > nowTime + 1 && this.form.status != 1) {
                this.timeStatus = 1;
                if (nowStartTime > nowTime + 1) {
                    this.form.status = 0;
                } else if (nowStartTime < nowTime) {
                    this.form.status = 1;
                }
            } else if (nowEndTime < nowTime && this.form.status != 2) {
                this.timeStatus = 1;
                this.form.status = 2;
            } else if (nowStartTime > nowTime + 1 && this.form.status != 0) {
                this.timeStatus = 1;
                this.form.status = 0;
            }
            
        },
        handleSubmit() {
            var imageActivityList = '',
                brandTag = '';
            if(this.form.brandTag.length>0){
                var brandtag1 = [];
                this.form.brandTag.forEach(item=>{
                    if(item.val != ''){

                        brandtag1.push(item.val)
                    }
                })
                brandTag = brandtag1.toString()
            }else{
                brandTag = ''
            }
            
            if(this.form.imageActivityList != null && this.form.imageActivityList.length>0){
                imageActivityList = this.form.imageActivityList.toString()
            }else{
                imageActivityList = ''
            }
            var params = {
                data: {
                    id: "" + this.form.id,
                    storeNo: this.user.storeNo,
                    name: this.form.name,
                    notice: this.form.notice,
                    sort: this.form.sort.toString(),
                    status: this.form.status.toString(),
                    startTime: new Date(this.startTime).getTime(),
                    endTime: new Date(this.endTime).getTime(),
                    remark: this.form.remark,
                    imgUrl: this.form.imgUrl,
                    brandTag: brandTag,
                    brandTitle: this.form.brandTitle,
                    brandStory: this.form.brandStory,
                    imageList: this.form.imageList,
                    imageActivityList:imageActivityList
                }
            };
            if (this.form.name == "") {
                this.$message({
                    message: "活动名称不能为空",
                    type: "warning",
                    duration: 1500
                });
            } 
            // else if (this.form.brandId == "") {
            //     this.$message({
            //         message: "品牌不能为空",
            //         type: "warning",
            //         duration: 1500
            //     });
            // } 
            else if (this.form.brandStory == "") {
                this.$message({
                    message: "品牌故事不能为空",
                    type: "warning",
                    duration: 1500
                });
            } else if (
                this.form.sort == "" ||/^[1-9][0-9]?$/.test(+this.form.sort) == false){
                this.$message({
                    message: "活动排序不能为空，且只能为1-99整数",
                    type: "warning",
                    duration: 1500
                });
            } else if (this.form.imageList.length == 0) {
                this.$message({
                    message: "最少上传一张品牌图片",
                    type: "warning",
                    duration: 1500
                });
            } else if (this.form.imageList.length > 3) {
                this.$message({
                    message: "最多上传3张品牌图片",
                    type: "warning",
                    duration: 1500
                });
            } else if (this.startTime == "") {
                this.$message({
                    message: "请选择活动开始时间",
                    type: "warning",
                    duration: 1500
                });
            } else if (this.endTime == "") {
                this.$message({
                    message: "请选择活动结束时间",
                    type: "warning",
                    duration: 1500
                });
            } else if (
                new Date(this.endTime).getTime() <
                new Date(this.startTime).getTime()
            ) {
                this.$message({
                    message: "请正确选择开始结束时间",
                    type: "warning",
                    duration: 1500
                });
            } else if (this.form.imgUrl == "") {
                this.$message({
                    message: "请选择活动图片",
                    type: "warning",
                    duration: 1500
                });
            } else if (this.form.notice == "") {
                this.$message({
                    message: "活动公告不能为空",
                    type: "warning",
                    duration: 1500
                });
            } else {
                this.$confirm("确认修改并提交？").then(_ => {
                    this.$fetch.post(editActivity, params).then(res => {
                        this.$message({
                            message: res.message,
                            type: "success",
                            duration: 1000
                        });
                        setTimeout(() => {
                            this.$router.go(-1);
                        }, 1500);
                    }).catch(err => {
                        this.$message({
                            message: err.message,
                            type: "warning",
                            duration: 1000
                        });
                    });
                });
            }
        },
        upload(e) {
            const that = this;
            var files = e.target.files[0];
            let width, height;
            let reader = new FileReader();
            reader.onload = function(e) {
                var image = new Image();
                image.onload = function() {
                    width = image.width;
                    height = image.height;
                    if (width == height && width >= 200) {
                        that.uploadLoading = true;
                        that.$http.get(getQiniuToken, {
                            params: {
                                wxUid: "",
                                wxSid: ""
                            }
                        }).then(res1 => {
                            let config = {
                                headers: {
                                    "Content-Type": "multipart/form-data"
                                }
                            };
                            let formdata = new FormData(); //创建form对象
                            formdata.append("file", files, files.name);
                            formdata.append("chunk", "0"); //断点传输
                            formdata.append("chunks", "1");
                            formdata.append("token", res1.data.uptoken);
                            that.$http.post( "http://up-z1.qiniup.com",formdata,config).then(res2 => {
                                if (res2.data.key != "") {
                                    that.form.imgUrl =
                                        qiniuBaseUrl +
                                        res2.data.key +
                                        "?imageMogr2/thumbnail/300000@";
                                    that.$message({
                                        title: "提示",
                                        message: "图片上传成功",
                                        type: "success",
                                        duration: 1000
                                    });
                                    that.uploadLoading = false;
                                }
                            }).catch(err => {
                                that.$message({
                                    title: "提示",
                                    message: "图片上传失败",
                                    type: "error",
                                    duration: 1000
                                });
                            });
                        });
                    } else {
                        that.$message({
                            message: "图片要求不小于200*200方图",
                            type: "error",
                            duration: 1000
                        });
                    }
                };
                image.src = e.target.result;
            };
            reader.readAsDataURL(files);
        },
        deleteImgList(data) {
            this.form.imgUrl = "";
        },

        //上传图片
        uploadimg(e) {
            const that = this;
            var files = e.target.files;
            for (let i = 0; i < files.length; i++) {
                let width, height;
                let reader = new FileReader();
                reader.onload = function(e) {
                    var image = new Image();
                    image.onload = function() {
                        width = image.width;
                        height = image.height;
                        if (width >= 400) {
                            that.uploadLoading1 = true;
                            that.$http.get(getQiniuToken, {
                                params: {
                                    wxUid: "",
                                    wxSid: ""
                                }
                            }).then(res1 => {
                                let config = {
                                    headers: {
                                        "Content-Type":
                                            "multipart/form-data"
                                    }
                                };
                                let formdata = new FormData(); //创建form对象
                                formdata.append(
                                    "file",
                                    files[i],
                                    files[i].name
                                );
                                formdata.append("chunk", "0"); //断点传输
                                formdata.append("chunks", "1");
                                formdata.append("token", res1.data.uptoken);
                                that.$http.post("http://up-z1.qiniup.com",formdata,config).then(res2 => {
                                    if (res2.data.key != "") {
                                        that.form.imageList.push(
                                            qiniuBaseUrl +
                                                res2.data.key +
                                                "?imageMogr2/thumbnail/300000@"
                                        );
                                        that.form.imageList = that.form.imageList.slice(0,1)
                                        that.$message({
                                            title: "提示",
                                            message: "图片上传成功",
                                            type: "success"
                                        });
                                        that.uploadLoading1 = false;
                                    }
                                });
                            });
                        } else {
                            that.$message({
                                title: "提示",
                                message: "上传图片尺寸要求宽度不小于400",
                                type: "warning"
                            });
                        }
                    };
                    image.src = e.target.result;
                };
                reader.readAsDataURL(files[i]);
            }
        },
        //活动图片-9
        uploadActimg(e) {
            const that = this;
            var files = e.target.files;
            for (let i = 0; i < files.length; i++) {
                let width, height;
                let reader = new FileReader();
                reader.onload = function(e) {
                    var image = new Image();
                    image.onload = function() {
                        width = image.width;
                        height = image.height;
                        if (width >= 400) {
                            that.uploadLoading1 = true;
                            that.$http.get(getQiniuToken, {
                                params: {
                                    wxUid: "",
                                    wxSid: ""
                                }
                            }).then(res1 => {
                                let config = {
                                    headers: {
                                        "Content-Type":
                                        "multipart/form-data"
                                    }
                                };
                                let formdata = new FormData(); //创建form对象
                                formdata.append("file", files[i], files[i].name);
                                formdata.append("chunk", "0"); //断点传输
                                formdata.append("chunks", "1");
                                formdata.append("token", res1.data.uptoken);
                                that.$http.post("http://up-z1.qiniup.com", formdata, config).then(res2 => {
                                    if (res2.data.key != "" ) {
                                        if(that.form.imageActivityList==null){
                                            that.form.imageActivityList = []
                                        }
                                        that.form.imageActivityList.push(
                                            qiniuBaseUrl +
                                                res2.data.key +
                                                "?imageMogr2/thumbnail/300000@"
                                        );
                                        that.form.imageActivityList = that.form.imageActivityList.slice(0,9)
                                        that.$message({
                                            title: "提示",
                                            message: "图片上传成功",
                                            type: "success"
                                        });
                                        that.uploadLoading1 = false;
                                    }
                                });
                            });
                        } else {
                            that.$message({
                                title: "提示",
                                message: "上传图片尺寸要求宽度不小于400",
                                type: "warning"
                            });
                        }
                    };
                    image.src = e.target.result;
                };
                reader.readAsDataURL(files[i]);
            }
        },
        deleteImgList1(i) {
            this.form.imageList.splice(i, 1);
        },
        deleteImgList2(j) {
            this.form.imageActivityList.splice(j, 1);
        },
        goToPrev(idx) {
            let newImg = this.form.imageList.slice();
            if (idx > 0) {
                let now = newImg[idx].toString();
                let prev = newImg[idx - 1].toString();
                newImg[idx] = prev;
                newImg[idx - 1] = now;
            }
            this.form.imageList = newImg;
        },
        goToPrev1(idx) {
            let newImg = this.form.imageActivityList.slice();
            if (idx > 0) {
                let now = newImg[idx].toString();
                let prev = newImg[idx - 1].toString();
                newImg[idx] = prev;
                newImg[idx - 1] = now;
            }
            this.form.imageActivityList = newImg;
        }
    }
};
</script>

<style scoped lang="less">
    @import url("../../style/activity.less");
    h3 {
        margin: 20px 0;
    }
   
</style>